package com.primus.server.web.controller;


import com.primus.server.entity.store.Product;
import com.primus.server.entity.store.Store;
import com.primus.server.service.store.ProductService;
import com.primus.server.service.store.StoreService;
import com.primus.server.web.ResponseBase;
import com.primus.server.web.vo.ProductVO;
import com.primus.server.web.vo.StoreVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("store")
public class StoreController extends BaseController{

    private final StoreService storeService;
    private final ProductService productService;

    @Autowired
    public StoreController(StoreService storeService, ProductService productService){
        this.storeService = storeService;
        this.productService = productService;
    }

    @GetMapping(path = "/{id}")
    public ResponseBase<StoreVO> getStoreById(@PathVariable Long id) {
        Store store = this.storeService.findById(id);
        StoreVO storeVO = this.transfer(store, new StoreVO(), "products");
        storeVO.setProducts(store.getProducts().stream().map(s -> this.transfer(s, new ProductVO())).collect(Collectors.toList()));
        return this.success(storeVO);
    }

    @PostMapping(path = "/upsert")
    public ResponseBase<Void> upsert(@RequestBody StoreVO vo) {
        this.storeService.save(this.transfer(vo, new Store()));
        return this.success();
    }

    @DeleteMapping(value = "/{id}")
    public ResponseBase<Void> deleteUser(@PathVariable Long id) {
        this.storeService.deleteById(id);
        return this.success();
    }

    // product operation
    @PostMapping(path = "/{storeId}/product")
    public ResponseBase<Void> addProduct(@PathVariable Long storeId, @RequestBody ProductVO pvo) {
        Store store = this.storeService.findById(storeId);
        Product product = this.transfer(pvo, new Product());
        product.setStore(store);
        this.productService.save(product);
        return this.success();
    }

}
